<template>
  <div class="wrapper">
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="12">
        <div class="label">记录保存时间</div>
        <el-date-picker
            v-model="paramsState.date"
            type="datetimerange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions">
        </el-date-picker>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search"
                   @click="search">搜索
        </el-button>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-download"
                   @click="downloadList">导出
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table :data="tableData" v-loading="listLoading" border>
      <el-table-column prop="carNumber" label="车牌编号" align="center"/>
      <el-table-column prop="title" label="提示标题" align="center"/>
      <el-table-column prop="content" label="提示内容" align="center"/>
      <el-table-column prop="saveTime" label="记录保存时间" align="center"/>
      <el-table-column prop="weather" label="天气状况" align="center">
        <template v-slot="{ row }">
          {{ getWeather(row.weather) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button type="text" title="删除" style="color:#f46162;" @click="handleDelete(row, false)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination :current-page="paramsState.startpoint" :page-size="paramsState.nums" :total="paramsState.total"
                   :page-sizes="[5, 10, 20, 30]" style="padding: 20px 0"
                   layout="prev, pager, next, jumper, ->, sizes, total"
                   @current-change="currentChange" @size-change="sizeChange"/>

    <!-- 查看 or 编辑框-->
    <el-dialog :title="findData.readonly ? '查看' : '编辑'" width="800px" :visible.sync="Visible" @closed="resetDialog">
      <el-form v-loading="loading" size="small" class="formRow" label-position="top"
               :class="{ disabled: findData.readonly }">
        <el-row :gutter="70">
          <el-col v-for="(field, index) in fields" :key="index" :span="8">
            <el-form-item :label="field.label" :prop="field.prop">
              <el-input v-model="findData[field.prop]"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button v-if="!findData.readonly" type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {query_escort, Query_the_exit_prompt, Remove_exit_prompts} from "@/api/index"
import {exportExcel, get_head_img} from "@/utils/index"
import moment from "moment"

export default {
  name: "hint",
  data() {
    return {
      // 加载
      listLoading: false,
      // 详情弹窗
      Visible: false,
      updateVisible: false,
      // 搜索用户相关
      paramsState: {
        date: [],
        startpoint: 1,
        nums: 10,
        total: 0
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 用户列表相关
      tableData: [],
      // 详情加载中
      loading: false,
      type: 'rgxd',

      // 操作的数据信息
      findData: {
        carNumber: '',
        title: '',
        content: '',
        weather: '',
        saveTime: ''
      },
      fields: [
        {label: '车牌号', prop: 'carNumber', width: '', align: 'center'},
        {label: '标题', prop: 'title', width: '', align: 'center'},
        {label: '内容', prop: 'content', width: '', align: 'center'},
        {label: '天气', prop: 'weather', width: '', align: 'center'},
        {label: '保存时间', prop: 'saveTime', width: '', align: 'center'}
      ],
      weatherList: [{
        name: "晴",
        value: 1
      },
        {
          name: "阴",
          value: 2
        },
        {
          name: "雨",
          value: 3
        },
        {
          name: "雾",
          value: 4
        },
        {
          name: "雪",
          value: 5
        },
        {
          name: "冰冻",
          value: 6
        },
      ]
    }
  },
  methods: {
    // 导出
    async downloadList() {
      let params = {
        ...this.paramsState,
        nums: 9999
      }
      if (params.date.length === 2) {
        let [starttime, endtime] = params.date;
        params.starttime = starttime;
        params.endtime = endtime;
      }
      delete params.date;
      delete params.total;

      let {data} = await Query_the_exit_prompt(params)
      console.log(data);
      data = data.map(item => {
        item.weather = this.getWeather(item.weather);
        return item;
      })

      const fields = ['carNumber', 'title', 'content', 'saveTime', 'weather'];
      const headers = ['车牌编号', '提示标题', '提示内容', '记录保存时间', '天气状况'];
      exportExcel(data, fields, headers, `出车提示-${moment().format(`YYYY-MM-DD HH:mm:ss`)}.xlsx`)
    },
    getWeather(value) {
      return this.weatherList.find(item => item.value == value).name;
    },
    dateFormat(date) {
      let expirationDate = moment(date)
      // 获取当前时间
      let now = moment()
      // 计算时间差
      let duration = moment.duration(expirationDate.diff(now)).days()
      if (duration < 0) {
        return "已过期"
      } else {
        return duration + "天"
      }
    },
    change(file) {
      let _this = this
      console.log(file.raw)
      let reader = new FileReader()
      reader.onload = function (event) {
        let base64 = event.target.result
        _this.findData.headimg = base64
      }
      reader.readAsDataURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const types = ['image/jpeg', 'image/png']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!types.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    format(time, end = "HH:mm:ss") {
      return moment(time).format(`YYYY-MM-DD ${end}`)
    },
    // 获取用户列表数据
    async getList() {
      this.listLoading = true
      try {
        let params = {
          ...this.paramsState
        }
        if (params.date.length === 2) {
          let [starttime, endtime] = params.date;
          params.starttime = starttime;
          params.endtime = endtime;
        }
        delete params.date;
        delete params.total;

        let result = await Query_the_exit_prompt(params)
        this.tableData = result.data
        this.listLoading = false

        this.paramsState.total = result.total;
        console.log(result.data)
      } catch (error) {
        this.listLoading = false
        this.$message.error("获取列表失败，请重试")
      }
    },
    // 根据用户输入进行查询
    search() {
      this.paramsState.startpoint = 1
      this.getList()
    },
    sizeChange(e) {
      this.paramsState.nums = e
      this.getList()
    },
    currentChange(e) {
      this.paramsState.startpoint = e
      this.getList()
    },
    resetDialog() {
      this.findData = {}
    },
    // 保存
    onSubmit() {
      let {content, title} = this.findData
      let params = {content, title}
      console.log(params, "提交参数")

      update_chucheInfo(params).then(result => {
        console.log(result, "处理订单")
        this.$message.success(result.msg)
        this.getList()
        this.Visible = false
      })
    },
    // 显示详情
    handle(row, readonly = false) {
      let params = {
        ...row,
        readonly
      }
      this.findData = params
      this.Visible = true
    },
    // 操作
    update(row) {
      this.findData = {
        id: row.id
      }
      this.updateVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Remove_exit_prompts({id: row.id}).then(() => {
          this.$message({
            type: 'success', message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {

      })
    }
  },
  async mounted() {
    await this.getList()
  }
}
</script>

<style lang="scss" scoped>
.table-avatar {
  width: 40px;
  height: 40px;
}

::v-deep .image-table-slot {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #eee;
}

.wrapper {
  margin: 20px;

  .label {
    font-size: 14px;
    color: #333;
    padding-bottom: 10px;
  }
}

::v-deep .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

.formRow {

  &.disabled {
    pointer-events: none;
  }


  .el-col {
    padding: 8px 0;

    .label {
      font-weight: 500;
      margin-right: 10px;
      color: #444;
    }

    .headimg_view {
      margin-left: 50%;
      transform: translateX(-50%);
      overflow: hidden;

      .avatar {
        width: 120px;
        height: 120px;
        font-size: 0;
      }

      ::v-deep .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        background-color: #eee;

        .iocn {
          font-size: 20px;
        }

        span {
          font-size: 14px;
        }
      }
    }
  }

  .sourceList {
    .item {
      padding: 10px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #ddd;

      &:last-child {
        border-bottom: 0;
      }

      .box {
        padding: 5px 0;
        display: flex;

        .label {
          color: #666;
          padding-right: 20px;
        }
      }
    }
  }
}

.dataList {
  margin-bottom: 20px;

  .desc {
    margin-top: 10px;
    color: #888;
  }

  .dataTitle {
    font-weight: 500;
    color: #333;
  }
}

//::v-deep .el-form-item__label {
//  width: 100%;
//}

.flex {
  display: flex;

  span {
    b {
      color: #f46162;
    }
  }

  &.between {
    justify-content: space-between;
  }
}
</style>
